package com.example.provider.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.common.entity.*;
import com.example.provider.dao.BiddingDao;
import com.example.provider.dao.CompanyDao;
import com.example.provider.dao.InviteDao;
import com.example.provider.dao.WorkroomDao;
import com.example.provider.service.CompanyService;
import com.example.provider.utils.IdWorker;
import org.apache.logging.log4j.util.PropertySource;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Service
public class CompanyServiceImpl implements CompanyService {
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private BiddingDao biddingDao;
    @Autowired
    private WorkroomDao workroomDao;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 发布需求
     */
    public Message releaseReq(Demand demand) throws IOException {
        //雪花算法生成自增id
        IdWorker idWorker = new IdWorker(1, 1, 1);
        Demand newDemand = new Demand(idWorker.nextId(), demand.getLable(), demand.getMoney(), demand.getPhone(),
                1, demand.getDescription(), demand.getCompanyId());
        //创建请求
        IndexRequest request = new IndexRequest("demo_demand");
        //规则 put /z_index/_doc/1
        //将我们的数据放入请求
        request.source(JSON.toJSONString(newDemand), XContentType.JSON);
        //客户端发送请求，获取响应的结果
        IndexResponse index =
                restHighLevelClient.index(request, RequestOptions.DEFAULT);
        return new Message(200, "发布需求成功");
    }

    /**
     * 搜索公司
     * @param id 当前用户id
     * @return
     */
    public Company searchByIdd(int id) {
        return companyDao.searchByIdd(id);
    }

    /**
     * 根据公司id搜索对应的招标情况
     * @param id 公司id
     * @return
     * @throws IOException
     */
    public List<Demand> checkBiddingByCompany(int id) throws IOException {
        //1、根据公司id去寻找对应的需求，并把状态赋给需求
        List<Demand> demands = new ArrayList<>();
        SearchRequest request = new SearchRequest("demo_demand");
        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermQueryBuilder queryBuilder =
                QueryBuilders.termQuery("companyId", id);
        builder.query(queryBuilder);
        request.source(builder);
        SearchResponse response =
                restHighLevelClient.search(request, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits().getHits()) {
            Map map = hit.getSourceAsMap();
            Demand d = new Demand(Long.parseLong(map.get("id").toString()), map.get("lable").toString(),
                    (double)map.get("money"), map.get("phone").toString(),(int)map.get("status"),
                    map.get("description").toString());
            demands.add(d);
        }
        return demands;
    }

    /**
     * 根据需求id搜索对应的竞标工作室排名
     * @param demandId 需求id
     * @return
     */
    public List<WorkRoom> searchWorkroomByDemandId(int demandId) {
        List<WorkRoom> workRooms = new ArrayList<>();
        //1、找出需求id对应的biddings
        List<Bidding> biddings = biddingDao.searchByGroupId(demandId);

        //2、根据这些bidding中的workroomId找到对应的workroom
        for (Bidding bidding : biddings) {
            WorkRoom workRoom = workroomDao.searchById(bidding.getWorkroomId());
            //存入竞标中计算出的工作室评分用于传给前端
            workRoom.setGrade(bidding.getGrade());
            workRooms.add((workRoom));
        }

        workRooms.sort(Comparator.comparing(WorkRoom::getGrade).reversed());

        return workRooms;
    }

    /**
     * 删除需求,要同时把竞标关系中相关的也删掉
     * @param demand 要删除的需求
     * @return
     */
    public Message deleteDemand(Demand demand) {
        //1、es中删除需求
        return null;
    }

    //公司注册
    @Transactional
    public Message applyCompany(Company company) {
        Company c = new Company();
        c.setCompanyName(company.getCompanyName());
        c.setCompanyNo(company.getCompanyNo());
        c.setPhotoUrl(company.getPhotoUrl());
        c.setIntroduce(company.getIntroduce());
        c.setApplyDocUrl(company.getApplyDocUrl());
        c.setLeaderName(company.getLeaderName());
        c.setStates(company.getStates());
        companyDao.insertCompany(c);
        return  new Message(800,"成功",company);
    }
}
